import React from "react";
import {connect} from 'dva';
import {Button, Form, Icon, message, Modal, Spin, Upload} from "antd";

const {Dragger} = Upload;

@connect(({commonModel}) => ({
    commonModel,
}))
class ExportModal extends React.Component {

    state = {
        //-- 记载层
        loading: false,
        //-- [true]:显示导入窗口, [false]:关闭导入窗口
        isShowExportModal: false,
        //--
        excelDemoHref: '',
        //-- 文件列表
        fileList: [],
        //-- 上传类型
        uploadType: ''
    }

    componentDidMount() {
        const {onRef, parent} = this.props;
        this.parent = parent;
        if (onRef) {
            onRef(this);
        }
    }

    handlerExportModal = (type) => {
        this.setState({
            isShowExportModal: true,
        })
        if (type == 'insurance') {
            this.setState({
                excelDemoHref: 'https://xiaobai-pdf-product.oss-cn-shenzhen.aliyuncs.com/doc/proposal/toubaoqingdan.xlsx',
                uploadType: type
            })
        } else if (type == 'account') {
            this.setState({
                excelDemoHref: 'https://xiaobai-pdf-product.oss-cn-shenzhen.aliyuncs.com/doc/proposal/yonghu.xls',
                uploadType: type
            })
        }
    }

    handlerUpload = (uploadType) => {
        const thisCtx = this;
        let formTye;
        if (uploadType == 'insurance') {
            formTye = '9';
        } else if (uploadType == 'account') {
            formTye = '8';
        }
        const {fileList} = this.state;
        if (fileList.length != 1 || !fileList[0].type.includes('application/vnd.ms-excel') && !fileList[0].type.includes('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) {
            message.error('请上传Excel文件！')
            return;
        }
        console.log(fileList);

        thisCtx.setState({loading: true});
        this.fileUpload(
            fileList[0].originFileObj,
            formTye,
            '-1',
            function (data) {
                thisCtx.setState({loading: false});
                if (data && data.success) {
                    message.info('导入成功！');
                    thisCtx.handlerCancel();
                    thisCtx.parent.findPageData();
                } else {
                    message.error(data.msg);
                }
            }
        );
    }

    handlerCancel = (isShowExportModal = false) => {
        let {loading, fileList} = this.state;
        if (loading) return;
        fileList = [];
        this.setState({isShowExportModal, fileList});
    }

    fileUpload = (file, formType, formId, callback) => {
        const {dispatch} = this.props,
            formData = new window.FormData();
        formData.append('file', file);
        formData.append('formType', formType);
        formData.append('formId', formId);
        dispatch({
            type: 'commonModel/fileUploadOfText',
            payload: formData,
            callback: callback
        });
    };

    render() {
        const thisCtx = this;

        const {loading, fileList, uploadType, isShowExportModal, excelDemoHref} = thisCtx.state;

        let {uploadHref} = this.props;

        const DraggerProps = {
            accept: '.xlsx,.xls',
            multiple: false,
            fileList: fileList,
            beforeUpload: function () {
                return false;
            },
            //-- 上传前检测文件
            // beforeUpload: file => {
            //     const fileType = file.type;
            //     console.log(fileType);
            //     //-- 检查文件
            //     if (!fileType.includes('application/vnd.ms-excel') && !fileType.includes('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) {
            //         message.error('请上传doc或pdf类型文件！');
            //         return false;
            //     }
            //     //-- 文件大小检测
            //     const checkFileSize = file.size / 1024 / 1024 < 10;
            //     if (!checkFileSize) {
            //         message.error('文件必须小于10MB!');
            //         return false;
            //     }
            //     console.log(file);
            //     return true;
            // },
            onChange(info) {
                let status = info.file.status;
                if (status === 'uploading') return;
                let fileList = [...info.fileList];
                fileList = fileList.slice(-1);
                fileList = fileList.map(file => {
                    if (file.response) {
                        file.url = file.response.url;
                    }
                    return file;
                });
                console.log(fileList);
                thisCtx.setState({fileList});
            },
        };

        const uploadName = {
            insurance: '报价表',
            account: '账户数据'
        }

        return (
            <Spin spinning={loading}>
                <Modal
                    visible={isShowExportModal}
                    width={550}
                    footer={false}
                    onCancel={() => this.handlerCancel()}>
                    <div style={{textAlign: 'center'}}>
                        <div style={{marginTop: '30px', color: 'black', fontSize: 20, fontWeight: 900}}>确认要导入表格
                        </div>
                        <div style={{marginTop: '20px'}}>
                            <em style={{
                                color: 'fade(@black, 45%)',
                                fontStyle: 'normal'
                            }}>提示：首次导入{uploadName[uploadType]}<Icon type="question-circle-o"/></em>&nbsp;&nbsp;
                            <a href={excelDemoHref}
                               download={true} style={{color: '#21BA63'}}>下载导入{uploadName[uploadType]}模板</a>
                        </div>
                        <div style={{marginTop: '20px'}}>
                            <Dragger {...DraggerProps}>
                                <p className="ant-upload-drag-icon">
                                    <Icon type="inbox"/>
                                </p>
                                <p className="ant-upload-text">单击或拖动文件到该区域以上传</p>
                                <p className="ant-upload-hint">
                                    注意:请使用导入模板上传数据,仅支持上传单个模板文件!
                                </p>
                            </Dragger>
                        </div>
                        <div style={{margin: '50px 0px 20px 0px'}}>
                            <Button size={'large'} type={'primary'}
                                    onClick={() => this.handlerUpload(uploadType)}>开始导入</Button>
                        </div>
                    </div>
                </Modal>
            </Spin>
        );
    }
}

export default Form.create()(ExportModal);
